<template>
  <div class="role">
    <div class="top-control mb-primary">
      <el-button type="primary" :icon="useRenderIcon(plus)" @click="add"
        >新增</el-button
      >
    </div>
    <div class="my-table mt-primary">
      <el-table
        :data="tableData"
        style="width: 100%"
        v-loading="listLoading"
        stripe
        border
      >
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="角色编号" prop="roleId" width="120" />
        <el-table-column
          label="角色名称"
          prop="roleName"
          :show-overflow-tooltip="true"
          width="150"
        />
        <el-table-column
          label="权限字符"
          prop="roleKey"
          :show-overflow-tooltip="true"
          width="150"
        />
        <el-table-column label="显示顺序" prop="roleSort" width="100" />
        <el-table-column
          label="创建时间"
          align="center"
          prop="createTime"
          width="180"
        >
          <template v-slot="scope">
            <span>{{ parseTime(scope.row.createTime) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center">
          <template v-slot="scope">
            <el-button
              type="primary"
              size="small"
              :icon="useRenderIcon(edit)"
              @click="editItem(scope.row)"
            />
            <el-button
              type="primary"
              :icon="useRenderIcon(iconDel)"
              size="small"
              @click="del(scope.row)"
            />
          </template>
        </el-table-column>
      </el-table>
    </div>
    <!-- 添加编辑弹窗 -->
    <el-dialog
      v-model="dialogVisible"
      :title="isEdit ? '编辑角色' : '新增角色'"
      width="650px"
      @closed="closed"
    >
      <div class="dialog-content">
        <el-form
          :model="form"
          :rules="rules"
          label-width="100px"
          ref="ruleFormRef"
        >
          <el-form-item label="角色名称" prop="roleName">
            <el-input v-model="form.roleName" placeholder="请输入角色名称" />
          </el-form-item>
          <el-form-item prop="roleKey">
            <template v-slot:label>
              <span>
                <el-tooltip
                  content="控制器中定义的权限字符，如：@PreAuthorize(`@ss.hasRole('admin')`)"
                  placement="top"
                >
                  <i class="el-icon-question" />
                </el-tooltip>
                权限字符
              </span>
            </template>
            <el-input v-model="form.roleKey" placeholder="请输入权限字符" />
          </el-form-item>
          <el-form-item label="角色顺序" prop="roleSort">
            <el-input-number
              v-model="form.roleSort"
              controls-position="right"
              :min="0"
            />
          </el-form-item>
          <el-form-item label="备注">
            <el-input
              v-model="form.remark"
              type="textarea"
              placeholder="请输入内容"
            />
          </el-form-item>
        </el-form>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submit" :loading="isLoading">
            确定
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { parseTime } from "@/utils/utils";
import { useRenderIcon } from "@/components/ReIcon/src/hooks";
import plus from "@iconify-icons/ep/plus";
import iconDel from "@iconify-icons/ep/delete";
import edit from "@iconify-icons/ep/edit";
import { reactive, ref } from "vue";
import { delRole, getAllRole, addRole, editRole } from "@/api/system/index";
import {
  ElMessage,
  ElMessageBox,
  FormRules,
  type FormInstance
} from "element-plus";
import type { AddRole, RoleRow } from "@/api/system/system";
import { onMounted } from "vue";
defineOptions({
  name: "role"
});
onMounted(() => {
  getList();
});
const tableData = ref<RoleRow[]>([]);
const listLoading = ref(false);
const getList = async () => {
  listLoading.value = true;
  const res = await getAllRole();
  if (res.code === 200) {
    tableData.value = res.rows;
    listLoading.value = false;
  }
};
const form = ref<AddRole>({
  roleName: "",
  roleKey: "",
  roleSort: 1,
  status: "0",
  menuIds: [],
  deptIds: [],
  menuCheckStrictly: true,
  deptCheckStrictly: true,
  remark: ""
});

const rules = reactive<FormRules>({
  roleName: [{ required: true, message: "角色名称不能为空", trigger: "blur" }],
  roleKey: [{ required: true, message: "权限字符不能为空", trigger: "blur" }],
  roleSort: [{ required: true, message: "角色顺序不能为空", trigger: "blur" }]
});
const ruleFormRef = ref<FormInstance>();
// 添加
const add = () => {
  isEdit.value = false;
  dialogVisible.value = true;
};
// 编辑
const currentRole = ref<RoleRow>();
const editItem = (item: RoleRow) => {
  for (const key in form.value) {
    form.value[key] = item[key];
  }
  currentRole.value = item;
  isEdit.value = true;
  dialogVisible.value = true;
};
// 删除
const del = (item: RoleRow) => {
  ElMessageBox.confirm("您确定要删除吗？", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning"
  }).then(async () => {
    const res = await delRole(item.roleId);
    if (res.code === 200) {
      ElMessage({
        type: "success",
        message: "删除成功"
      });
      getList();
    }
  });
};
// 弹窗
const dialogVisible = ref(false);
const isEdit = ref(false);
const closed = () => {
  form.value = {
    roleName: "",
    roleKey: "",
    roleSort: 1,
    status: "0",
    menuIds: [],
    deptIds: [],
    menuCheckStrictly: true,
    deptCheckStrictly: true,
    remark: ""
  };
  ruleFormRef.value.clearValidate();
};
// 添加提交
const addSubmit = async () => {
  const res = await addRole(form.value);
  if (res.code === 200) {
    ElMessage.success("添加成功");
  }
};
// 编辑提交
const editSubmit = async () => {
  const res = await editRole({
    ...currentRole.value,
    ...form.value
  });
  if (res.code === 200) {
    ElMessage.success("修改成功");
  }
};
// 提交
const isLoading = ref(false);
const submit = () => {
  ruleFormRef.value.validate(async valid => {
    if (valid) {
      isLoading.value = true;
      if (isEdit.value) {
        await editSubmit();
      } else {
        await addSubmit();
      }
      isLoading.value = false;
      dialogVisible.value = false;
      getList();
    }
  });
};
</script>
